import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject)
    return originalPush.call(this, location, resolve, reject);
  return originalPush.call(this, location).catch((err) => err);
};

// 路由映射数组
const routes = [
  {
    path: '/',
    redirect:'/home',
    component: () => import('@/views/layout'),
    children: [
      {
        path: 'home',
        component:() => import('@/views/layout/home')
      },
      {
        path: 'qa',
        component:() => import('@/views/layout/qa')
      },
      {
        path: 'video',
        component:() => import('@/views/layout/video')
      },
      {
        path: 'my',
        component:() => import('@/views/layout/my')
      },
    ]
  },
  {
    path: '/login',
    component:() => import('@/views/login')
  },
  {
    path: '/user/collect',
    component: () => import('@/views/user/collect'),
    //路由源信息,给每个路由一些自定义数据
    //需要登录才可以访问的页面给他设置needLogin设置为true
    meta: {
      needLogin:true
    }
  },
  {
    path: '/user/history',
    component: () => import('@/views/user/history'),
    meta: {
      needLogin:true
    }
  },
  {
    path: '/search',
    component:() =>import('@/views/search')
  },
  {
    path: '/article/:id',
    component:() => import('@/views/article')
  },
  {
    path: '/user/edit',
    component: () => import('@/views/user/edit'),
    meta: {
      needLogin:true
    }
  }
]
// 实例化路由对象
const router = new VueRouter({
  routes
})

//导航守卫
router.beforeEach((to, from, next) => {
  //注意一定要next(),否则路由会被挂起来,不会跳转截面
  // console.log(to);
  // console.log(from);
  if (to.meta.needLogin) {
    //取得界面需要登录,则要判断是否登录
    if (store.getters.token) {
      //登录了则放行
      next()
    } else {
      //没有登录则跳转登录页
      next(`/login?url=${to.path}`)
    }
  } else {
    //不需要登录,则直接放行
  next()

  }
})

export default router